<?php
header('Content-type: text/javascript');
?>
var tinyMCELinkList = new Array(
<?php

$output = array();
page_list();
$output[] = "['','']";
$output[] = "['Files','']";
$output[] = "['=========','']";
file_list();

for ($i=0;$i<sizeof($output);$i++) {
	echo $output[$i];	
	if ($i == sizeof($output) - 1) echo "\n";
	else echo ",\n";
}

function page_list($parent_id=null, $current_path='') {
	global $output, $db, $site, $env;
	
	if ($parent_id == null) {
		// get the top most page
		list($parent_id, $title) = array_values($db->fetchRow("SELECT p.id, title FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE site_id=? AND parent_id=0", $site['id']));
		if (!$parent_id) {
			exit;
		}
		$output[] = "['/', '/']";
		
	}
	
	$pages = $db->fetchAll("SELECT p.id, r.title, r.path, r.link FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE p.site_id=? AND p.parent_id=? AND active=1 ORDER BY sort", array($site['id'], $parent_id));
	for($i=0;$i<count($pages);$i++) {
		$pages[$i]['full_path'] =  $current_path . '/' . $pages[$i]['path'];
		$output[] = "['{$pages[$i]['full_path']}', '{$pages[$i]['full_path']}']";
		$pages[$i]['children'] = page_list($pages[$i]['id'], $pages[$i]['full_path']);
	}
	
}

function file_list($parent_id=null, $parent_folders='') {
	global $output, $db, $site, $env;
	
	if ($parent_id == null) {
		// get the top most folder
		$parent_id = $db->fetchOne("SELECT id FROM cms_files_folders WHERE site_id=? AND parent_id=0", $site['id']);
		if (!$parent_id) {
			exit;
		}
	}
	
	$files = $db->fetchAll("SELECT id, filename FROM cms_files WHERE site_id=? AND folder_id=? ORDER BY caption, filename", array($site['id'], $parent_id));
	foreach($files as $file) {
		$file['id'] = str_pad($file['id'], 5, 0, STR_PAD_LEFT);
		$output[] = "['{$parent_folders}{$file['filename']}', '/files/{$file['id']}/{$file['filename']}']";
	}
	
	$subfolders = $db->fetchAll("SELECT id, title FROM cms_files_folders WHERE site_id=? AND parent_id=?", array($site['id'], $parent_id));
	foreach($subfolders as $subfolder) {
		file_list($subfolder['id'], "{$parent_folders}{$subfolder['title']} » ");
	}

}

?>
);